﻿using Pay.Core;
using Pay.Data;
using Pay.DTO;
using Pay.IService;
using Pay.TO;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;

namespace Pay.Service.Service {

    public class MarketingPromoterService : ServiceBase, IMarketingPromoterService, IDisposable {
        private IUnitOfWork _iUnitOfWork;
        private IMarketingCommonService _iMarketingCommonService;
        private ITokenStatisticsService _iTokenStatisticsService;
        private ITokenGradeService _iTokenGradeService;
        private ISettingService _iSettingService;
        private IMerchantService _merchantService;
        public MarketingPromoterService(IUnitOfWork iUnitOfWork, IMarketingCommonService iMarketingCommonService, ITokenStatisticsService iTokenStatisticsService,
            ITokenGradeService iTokenGradeService, ISettingService iSettingService, IMerchantService merchantService) : base(iUnitOfWork) {
            this._iUnitOfWork = iUnitOfWork;
            _iMarketingCommonService = iMarketingCommonService;
            _iTokenStatisticsService = iTokenStatisticsService;
            _iTokenGradeService = iTokenGradeService;
            _iSettingService = iSettingService;
            _merchantService = merchantService;
        }

        #region 我的业务员
        /// <summary>
        /// 获取我的业务员信息
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public marketing_user_promoter_info_dto GetMyPromoterInfo(long userId) {
            var result = new marketing_user_promoter_info_dto();
            List<marketing_user_child_model> myChildList = _iMarketingCommonService.GetMyChidListNoHasCityChilds(userId, true);//我的下级（我的市分公司下级，排除其的子级）
            if (myChildList == null || myChildList.Count() == 0) return result;
            var myDirectList = myChildList.Where(o => o.ParentId == userId).ToList();//我的直接下级
            var myIndirectChildList = myChildList.Where(o => o.ParentId != userId).ToList();//我的间接下级

            var curMerchant = _merchantService.Get(userId);
            if (curMerchant.merchant_no == t_RequestMethod.TOKEN_MARKETING_DEFAULT_MEARCHANTNO) {
                myDirectList = myChildList.Where(o => o.ParentId == 0).ToList();//我的直接下级
                myIndirectChildList = myChildList.Where(o => o.ParentId != 0).ToList();//我的间接下级
            }

            if (myDirectList != null) {
                result.direct_promoter_num = myDirectList.Count();//直营业务员数量
                result.maker_num = myDirectList.Where(o => o.UserType == UserType.tokenMaker).Count();//直营创客数量
                result.node_mall_num = myDirectList.Where(o => o.UserType == UserType.tokenNodeMall).Count(); //直营节点商城数量
                result.super_node_num = myDirectList.Where(o => o.UserType == UserType.tokenCountyAgent).Count();//直营超级节点数量
                result.city_agent_num = myDirectList.Where(o => o.UserType == UserType.tokenCityAgent).Count();//直营市分公司
            }
            if (myIndirectChildList != null) {
                result.indirect_promoter_num = myIndirectChildList.Count();//加盟业务员数量
                result.maker_num += myIndirectChildList.Where(o => o.UserType == UserType.tokenMaker).Count();//加间接创客数量
                result.node_mall_num += myIndirectChildList.Where(o => o.UserType == UserType.tokenNodeMall).Count(); //加间接节点商城数量
                result.super_node_num += myIndirectChildList.Where(o => o.UserType == UserType.tokenCountyAgent).Count();//加间接超级节点数量
                result.city_agent_num += myIndirectChildList.Where(o => o.UserType == UserType.tokenCityAgent).Count();//加间接分公司
            }

            var tokenStatistics = _iTokenStatisticsService.GetOrCreate(userId);
            if (tokenStatistics != null) {
                result.allow_marker_num = tokenStatistics.total_surplus_open_maker;
            }
            return result;

        }

        /// <summary>
        /// 购买节点名额
        /// </summary>
        /// <param name="model"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public bool BuyMakerQuota(buy_maker_quota_model model, long userId) {
            if (model.buy_num < 1)
                throw new ServerErrorException("购买数量不能小于1");
            if (string.IsNullOrEmpty(model.mobile))
                throw new ServerErrorException("请输入联系方式");
            QuotaRecord quotaRecord = new QuotaRecord {
                ApplyNum = model.buy_num,
                ApplyTime = DateTime.Now.ToUnix(),
                EQuotaRecordAudit = EQuotaRecordAudit.PendingAudit,
                MerchantId = userId,
                Moblie = model.mobile
            };
            var merchant_dto = _merchantService.Get(userId);
            if (merchant_dto.merchant_no == t_RequestMethod.TOKEN_MARKETING_DEFAULT_MEARCHANTNO) {
                quotaRecord.MerchantName = merchant_dto.name;
            } else {
                var authInfo = _merchantService.GetAuth(userId);
                if (authInfo != null) {
                    quotaRecord.MerchantName = authInfo.account_name;
                }
            }
            context.QuotaRecord.Add(quotaRecord);
            return _iUnitOfWork.Commit() > 0;
        }
        /// <summary>
        /// 申请发展业务员
        /// </summary>
        /// <param name="model"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public bool ApplyOpenUserType(apply_user_type_model model, long userId) {
            var oem = _merchantService.Get(t_RequestMethod.merchant_no);
            var applyMerchant = context.Merchants.Where(o => o.Mobile == model.mobile && o.IsOEM == false && o.OemId == oem.id).FirstOrDefault();
            if (applyMerchant == null)
                throw new ServerErrorException("开通账号不存在");
            var cur_merchant_dto = _merchantService.Get(userId);//发出邀请的用户


            //判断只允许由上级开通账号，且不能跨越市级代理
            if (applyMerchant.ParentId > 0) {
                var parents = _merchantService.GetParents(applyMerchant.ParentId);
                if (!parents.Any(c => c.id == userId) && cur_merchant_dto.merchant_no != t_RequestMethod.TOKEN_MARKETING_DEFAULT_MEARCHANTNO)
                    throw new ServerErrorException("只能由上级开通账号");

                var applyCityCompany = _iMarketingCommonService.GetCityCompanyMerchantByMerchantId(applyMerchant.Id);
                var curCityCompany = _iMarketingCommonService.GetCityCompanyMerchantByMerchantId(userId);
                if (applyCityCompany.id != userId && applyCityCompany.id != curCityCompany.id && cur_merchant_dto.merchant_no != t_RequestMethod.TOKEN_MARKETING_DEFAULT_MEARCHANTNO) {
                    throw new ServerErrorException("只能由上级(不能跨越市级代理)开通账号");
                }

            } else if (cur_merchant_dto.merchant_no != t_RequestMethod.TOKEN_MARKETING_DEFAULT_MEARCHANTNO) {
                throw new ServerErrorException("只能由上级开通账号");
            }

            if ((int)applyMerchant.UserType >= (int)model.user_type)
                throw new ServerErrorException(string.Format("开通账号已是：{0} 角色，不能申请：{1} 角色", applyMerchant.UserType.ToDescription(), model.user_type.ToDescription()));
            if (string.IsNullOrEmpty(model.transfer_voucher))
                throw new ServerErrorException("请上传转账凭证");
            TokenUpGrade tokenUpGrade = new TokenUpGrade() {
                MerchantId = userId,
                GradeId = model.user_type,
                ApplyMerchantId = applyMerchant.Id,
                TransferVoucher = model.transfer_voucher,
                ApplyTime = DateTime.Now.ToUnix(),
                EUpGradeAudit = EUpGradeAudit.PendingAudit,
            };
            if (context.TokenUpGrade.Exist(o => o.MerchantId == tokenUpGrade.MerchantId && o.GradeId == tokenUpGrade.GradeId && o.ApplyMerchantId == tokenUpGrade.ApplyMerchantId))
                throw new ServerErrorException("已存在相同记录的申请，请勿重复提交");
            //if (tokenUpGrade.GradeId == UserType.tokenMaker) {
            //    //申请创客
            //    if (cur_merchant_dto.usertype == UserType.tokenCityAgent)
            //        throw new ServerErrorException("非市级分公司，不能开通创客");
            //    TokenStatistics tokenStatistics = context.TokenStatistics.Where(o => o.MerchantId == userId).FirstOrDefault() ?? new TokenStatistics();
            //    if (tokenStatistics.TotalSurplusOpenMaker < 1) {
            //        throw new ServerErrorException("开通创客名额不足，不能开通");
            //    }
            //}

            tokenUpGrade.CityCompanyMerchantId = _iMarketingCommonService.GetCityCompanyMerchantByMerchantId(userId).id;

            if (cur_merchant_dto.merchant_no == t_RequestMethod.TOKEN_MARKETING_DEFAULT_MEARCHANTNO) {
                tokenUpGrade.MerchantName = cur_merchant_dto.name;
            } else {
                var authInfo = _merchantService.GetAuth(userId);
                if (authInfo != null) {
                    tokenUpGrade.MerchantName = authInfo.account_name;
                }
            }
            var cityMerchant = _iMarketingCommonService.GetCityCompanyMerchantByMerchantId(userId);
            var merchantReceivables = context.MerchantReceivables.Where(o => o.MerchantId == cityMerchant.id).FirstOrDefault();
            if (merchantReceivables == null) throw new ServerErrorException("邀请人市级分公司未填写收款账号信息");
            tokenUpGrade.ReceivablesInfo = merchantReceivables.ToDtoObject<recivables_dto>().ToJson();

            var tokenGrade = _iTokenGradeService.Get(tokenUpGrade.GradeId);
            if (tokenGrade == null) throw new ServerErrorException(string.Format("{0} 级别信息未配置", tokenUpGrade.GradeId.ToDescription()));
            tokenUpGrade.Amount = tokenGrade.upfee;

            context.TokenUpGrade.Add(tokenUpGrade);

            //增加消息记录给市级合伙人
            var msg_setting = _iSettingService.GetTokenSetting().msg;
            var msg = msg_setting.FirstOrDefault(s => s.code == "user_type_auditing");
            if (msg == null) throw new ServerErrorException("开通待审核消息类型未配置");
            MessagePush message = new MessagePush() {
                Title = msg.name,
                Content = msg.content,
                CreateTime = DateTime.Now.ToUnix(),
                MerchantId = tokenUpGrade.CityCompanyMerchantId,
                ShortContent = msg.content,
                Type = MsgType.Marketing,
                Ext = string.Empty,
                IsRead = false,
                Filter = false
            };
            context.MessagePushs.Add(message);

            return _iUnitOfWork.Commit("MessagePush" + message.MerchantId) > 0;
        }
        #endregion

        #region 邀请好友开通
        /// <summary>
        /// 邀请好友开通
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool InviteOpenUserType(invite_user_type_model_ex model) {
            if (model.mobile == model.invitation_mobile)
                throw new ServerErrorException("邀请人和开通账号不能相同");
            var oem = _merchantService.Get(t_RequestMethod.merchant_no);
            var invitationMerchant = context.Merchants.Where(o => o.Mobile == model.invitation_mobile &&
                                    ((o.IsOEM == false && o.OemId == oem.id) || o.MerchantNo == t_RequestMethod.TOKEN_MARKETING_DEFAULT_MEARCHANTNO)).FirstOrDefault();
            if (invitationMerchant == null)
                throw new ServerErrorException("发出邀请的账号不存在");
            apply_user_type_model applyUserTypeModel = new apply_user_type_model();
            model.ToCopyProperty(applyUserTypeModel);
            return ApplyOpenUserType(applyUserTypeModel, invitationMerchant.Id);
        }
        /// <summary>
        /// 根据手机号获得其市级分公司
        /// </summary>
        /// <param name="mobile"></param>
        /// <returns></returns>
        public merchant_dto GetCityCompanyMerchantByMobile(string mobile) {
            var oem = _merchantService.Get(t_RequestMethod.merchant_no);
            var invitationMerchant = context.Merchants.Where(o => o.Mobile == mobile &&
            ((o.IsOEM == false && o.OemId == oem.id) || o.MerchantNo == t_RequestMethod.TOKEN_MARKETING_DEFAULT_MEARCHANTNO)).FirstOrDefault();
            if (invitationMerchant == null)
                throw new ServerErrorException("发出邀请的账号不存在");

            return _iMarketingCommonService.GetCityCompanyMerchantByMerchantId(invitationMerchant.Id);
        }
        #endregion

        #region 详细列表
        /// <summary>
        /// 业务员详细分页列表
        /// </summary>
        /// <param name="query"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public PagedResult<promoter_list_model> GetPromoterPageList(MarketingPromoterQuery query, long userId) {
            List<SqlParameter> paramArray = new List<SqlParameter>();
            paramArray.Add(new SqlParameter("@user_id", userId));
            paramArray.Add(new SqlParameter("@promoter", string.IsNullOrEmpty(query.promoter) ? "" : query.promoter));
            paramArray.Add(new SqlParameter("@user_type", query.user_type));
            paramArray.Add(new SqlParameter("@begin_time", !string.IsNullOrEmpty(query.begin_time)? DateTime.Parse(query.begin_time).ToUnix() : 0));
            paramArray.Add(new SqlParameter("@end_time", !string.IsNullOrEmpty(query.end_time) ? DateTime.Parse(query.end_time).ToUnix() : 0));
            paramArray.Add(new SqlParameter("@page", query.page));
            paramArray.Add(new SqlParameter("@size", query.size));
            SqlParameter param = new SqlParameter("@total_result", SqlDbType.Int);
            param.Direction = ParameterDirection.Output;
            paramArray.Add(param);
            var rows = context.Database.SqlQuery<promoter_list_model>("EXEC [sp_view_Promoter] @user_id,@promoter,@user_type,@begin_time,@end_time,@page,@size,@total_result output", paramArray.ToArray()).ToList();
            int total_result = (int)paramArray[7].Value;
            var result = new PagedResult<promoter_list_model>(rows, total_result, query.page, query.size);
            return result;
        }
        #endregion

    }
}
